import React, { useState } from 'react';
// import axios from 'axios';
import './List.css';
import type { Message, ShowThinkState, StreamResponse } from '../../types/ai';
import ReactMarkdown from 'react-markdown';

function extractThinkTag(text: string): string {
  const match = text.match(/<think>[\s\S]*?<\/think>/);
  return match ? match[0].replace(/<\/?think>/g, '').trim() : '';
}

function filterThinkTags(text: string): string {
  return text.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
}

const openingStatement = '我能帮你查询数据并编写分析报告，让我们从一个问题开始吧!';
const openingQuestions = [
  '推荐几款适合我的产品',
  '销量最好的防晒产品是哪款?',
  '夏季主推产品是哪款?',
];

const DeepSeekChat: React.FC = () => {
  const [input, setInput] = useState<string>('');
  const [messages, setMessages] = useState<Message[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [showThink, setShowThink] = useState<ShowThinkState>({});
  const [showOpening, setShowOpening] = useState<boolean>(true);
  const API_KEY: string = 'app-0u5HyTfUgMKENP4JD6TWOorJ';

  // 新增：处理开场白问题点击
  const handleOpeningQuestion = async (question: string) => {
    setShowOpening(false);
    setMessages([{ role: 'assistant', content: openingStatement }, { role: 'user', content: question }]);
    setInput('');
    // 自动触发 handleSubmit 逻辑
    await handleSubmitSim(question);
  };

  // 新增：模拟 handleSubmit 但不依赖表单事件
  const handleSubmitSim = async (question: string): Promise<void> => {
    setIsLoading(true);
    const userMessage: Message = { role: 'user', content: question };
    // setMessages(prev => [...prev, userMessage]); // 已在 handleOpeningQuestion 里加入
    try {
      const response = await fetch('/api/v1/chat-messages', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          inputs: {},
          query: question,
          response_mode: "streaming",
          user: "Mzc"
        })
      });
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }
      if (!response.body) {
        throw new Error('No response body');
      }
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      const aiMessage: Message = { role: 'assistant', content: '' };
      setMessages(prev => [...prev, aiMessage]);
      let done = false;
      let buffer = '';
      while (!done) {
        const { value, done: doneReading } = await reader.read();
        done = doneReading;
        if (value) {
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() || '';
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data: StreamResponse = JSON.parse(line.slice(6));
                if (data.event === 'message') {
                  aiMessage.content += data.answer;
                  setMessages(prev => [...prev.slice(0, -1), { ...aiMessage }]);
                }
              } catch (e) {
                console.error('Error parsing stream data:', e);
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setIsLoading(false);
      setInput('');
    }
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
    e.preventDefault();
    if (!input.trim()) return;
    setIsLoading(true);
    const userMessage: Message = { role: 'user', content: input };
    setMessages(prev => [...prev, userMessage]);
    try {
      const response = await fetch('/api/v1/chat-messages', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          inputs: {},
          query: input,
          response_mode: "streaming",
          user: "Mzc"
        })
      });
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }
      if (!response.body) {
        throw new Error('No response body');
      }
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      const aiMessage: Message = { role: 'assistant', content: '' };
      setMessages(prev => [...prev, aiMessage]);
      let done = false;
      let buffer = '';
      while (!done) {
        const { value, done: doneReading } = await reader.read();
        done = doneReading;
        if (value) {
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() || '';
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data: StreamResponse = JSON.parse(line.slice(6));
                if (data.event === 'message') {
                  aiMessage.content += data.answer;
                  setMessages(prev => [...prev.slice(0, -1), { ...aiMessage }]);
                }
              } catch (e) {
                console.error('Error parsing stream data:', e);
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setIsLoading(false);
      setInput('');
    }
  };

  return (
    <div className="chat-container">
      {showOpening ? (
        <div className="opening-section" style={{ marginBottom: 24 }}>
          <div className="message assistant" style={{ marginBottom: 12 }}>
            <div className="avatar">
              <img src="https://cdn-icons-png.flaticon.com/512/4712/4712035.png" alt="ai" />
            </div>
            <div className="message-content">
              <div className="message-header">
                <span className="name">AI客服</span>
              </div>
              <div className="message-text">{openingStatement}</div>
            </div>
          </div>
          <div className="opening-questions" style={{ display: 'flex', gap: 12 }}>
            {openingQuestions.map((q, i) => (
              <button
                key={i}
                style={{ background: '#f3f4f6', border: 'none', borderRadius: 6, padding: '8px 16px', cursor: 'pointer', color: '#2563eb', fontSize: 14 }}
                onClick={() => handleOpeningQuestion(q)}
                disabled={isLoading}
              >
                {q}
              </button>
            ))}
          </div>
        </div>
      ) : null}
      <div className="messages">
        {messages.map((msg, index) => (
          <div key={index} className={`message ${msg.role}`}>
            <div className="avatar">
              {msg.role === 'user' ? (
                <img src="https://randomuser.me/api/portraits/men/32.jpg" alt="user" />
              ) : (
                <img src="https://cdn-icons-png.flaticon.com/512/4712/4712035.png" alt="ai" />
              )}
            </div>
            <div className="message-content">
              <div className="message-header">
                <span className="name">
                  {msg.role === 'user' ? '' : 'AI客服'}
                </span>
              </div>
              <div className="message-text">
                <ReactMarkdown>
                  {filterThinkTags(msg.content)}
                </ReactMarkdown>
                {msg.role === 'assistant' && /<think>[\s\S]*?<\/think>/.test(msg.content) && (
                  <>
                    <button
                      style={{ marginTop: 8, fontSize: 12, color: '#2563eb', background: 'none', border: 'none', cursor: 'pointer' }}
                      onClick={() => setShowThink(prev => ({ ...prev, [index]: !prev[index] }))}
                    >
                      {showThink[index] ? '隐藏深度思考' : '显示深度思考'}
                    </button>
                    {showThink[index] && (
                      <div style={{ marginTop: 6, background: '#f3f4f6', borderRadius: 6, padding: 8, fontSize: 13, color: '#666' }}>
                        {extractThinkTag(msg.content)}
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>
        ))}
        {isLoading && (() => {
          const lastMsg = messages[messages.length - 1];
          const showTyping = !messages.length || lastMsg.role !== 'assistant' || (lastMsg.role === 'assistant' && !lastMsg.content);
          return showTyping ? (
            <div className="message assistant thinking">
              <div className="avatar">
                <img src="https://cdn-icons-png.flaticon.com/512/4712/4712035.png" alt="ai" />
              </div>
              <div className="message-content">
                <div className="message-header">
                  <span className="name">AI客服</span>
                </div>
                <div className="message-text">
                  <span className="typing">
                    <span className="typing-dot"></span>
                    <span className="typing-dot"></span>
                    <span className="typing-dot"></span>
                  </span>
                </div>
              </div>
            </div>
          ) : null;
        })()}
      </div>
      <form className="input-area" onSubmit={handleSubmit}>
        <input
          type="text"
          value={input}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setInput(e.target.value)}
          disabled={isLoading}
          placeholder="输入你的问题..."
        />
        <button type="submit" disabled={isLoading}>
          发送
        </button>
      </form>
    </div>
  );
};

export default DeepSeekChat; 


